/**
 * 
 */
package server.connection.sending;


import server.EventDispatcher;
import server.connection.Protocol;
import server.connection.SelectorAdapter;
import server.connection.listening.SelectorThread;
import server.connection.protocol.Event;

/**
 * 
 * Module used to send messages to a particular or all logged clients
 * 
 * Sending adapter module is implemented as a standalone SendingAdapter object. 
 * 
 * @author Kamil Nowak
 * 
 */
public class SendingAdapter {

	private final static SendingAdapter instance = new SendingAdapter();
	
	private SendingAdapter() {}
	
	/**
	 * Gets standalone instance of SendingAdapter class
	 * @return standalone object
	 */
	public static SendingAdapter instance() {
		return instance;
	}

	/**
	 * Sends event to one client specifed by field connectionId in event object
	 * 
	 * @param event event to send
	 */
	public void send(Event event) {
		
		String msg = Protocol.instance().createMessage(event);
		SelectorThread selectorThread = SelectorAdapter.instance().getSelectorThread(event.getConnectionId());
		
		selectorThread.send(msg,event.getConnectionId());
		selectorThread.wakeup();
	}

	/**
	 * Sends event to all logged client
	 * @param event event to send
	 */
	public void sendAll(Event event) {
		String msg = Protocol.instance().createMessage(event);
		for (Long cc : EventDispatcher.instance().getIntroducedConnections()) {
			SelectorThread sc = SelectorAdapter.instance().getSelectorThread(cc); 
			sc.send(msg,cc);
			sc.wakeup();
		}
	}
	
}
